/* eslint-disable guard-for-in */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-shadow */
import React, { Fragment, useState, useEffect, useReducer } from 'react';
import { Card, Modal, notification, Button, message } from 'antd';
import Link from 'umi/link';
import {
  SIZE,
  PAGE,
  BIG_SIZE,
  STUDENT_DOWNLOAD_THEADER,
  STUDENT_DOWNLOAD_FILTER_VALUE,
} from '@/utils/constant';
import { studentsList, delStudent, Editstudents } from '@/services/api';
import MyForm from './components/MyForm';
import ApplyModal from './components/ApplyModal';
import OutModal from './components/OutModal';
import UpdateParentModal from './components/UpdateParentModal';
import TableList from './components/TableList';

interface initial {
  loading: boolean;
  data: [];
  pagination: object;
  searchValue: object;
}

const initialState: initial = {
  loading: false,
  data: [],
  pagination: {
    showSizeChanger: true,
  },
  searchValue: {},
};

const reducer = (state: any, { type, payload }: any) => {
  switch (type) {
    case 'OPEN_LOADING':
      return {
        ...state,
        loading: true,
      };
    case 'CLOSED_LOADING':
      return {
        ...state,
        loading: false,
      };
    case 'GET_DATA':
      return {
        ...state,
        data: payload,
      };
    case 'CHANGE_PAGINATION':
      return {
        ...state,
        pagination: payload,
      };
    case 'SEARCH_VALUE':
      return {
        ...state,
        searchValue: payload,
      };
    default:
      return state;
  }
};

function ApplyList() {
  const [addModal, setAddModal] = useState(false);
  const [outModal, setOutModal] = useState(false);
  const [parentModal, setParentModal] = useState(false);
  const [{ loading, data, pagination, searchValue }, dispatch]: any = useReducer(
    reducer,
    initialState,
  );
  const pager = JSON.parse(JSON.stringify(pagination));
  useEffect(() => {
    dispatch({
      type: 'OPEN_LOADING',
    });
    studentsList({ page: PAGE, size: SIZE })
      .then((res: any) => {
        if (res.status === 'success') {
          dispatch({
            type: 'GET_DATA',
            payload: res.data.data,
          });
          dispatch({
            type: 'CHANGE_PAGINATION',
            payload: {
              ...pager,
              total: res.data.meta.total,
            },
          });
        }
        dispatch({
          type: 'CLOSED_LOADING',
        });
      })
      .catch(() => {
        dispatch({
          type: 'CLOSED_LOADING',
        });
      });
  }, []);

  const onChange = (changePagination: any) => {
    pager.current = changePagination.current;
    pager.pageSize = changePagination.pageSize;
    dispatch({
      type: 'CHANGE_PAGINATION',
      payload: pager,
    });
    dispatch({
      type: 'OPEN_LOADING',
    });
    studentsList({
      ...searchValue,
      page: changePagination.current,
      size: changePagination.pageSize,
    })
      .then((res: any) => {
        if (res.status === 'success') {
          dispatch({
            type: 'GET_DATA',
            payload: res.data.data,
          });
          dispatch({
            type: 'CHANGE_PAGINATION',
            payload: {
              ...pager,
              total: res.data.meta.total,
            },
          });
        }
        dispatch({
          type: 'CLOSED_LOADING',
        });
      })
      .catch(() => {
        dispatch({
          type: 'CLOSED_LOADING',
        });
      });
  };

  function formatJson(filterVal: string[], jsonData: object[]) {
    return jsonData.map(v => filterVal.map(j => v[j]));
  }

  const downloadData = (type: number) => {
    dispatch({
      type: 'OPEN_LOADING',
    });
    let data: any;
    if (type === 1) {
      data = { page: PAGE, size: BIG_SIZE };
    } else if (type === 2) {
      data = { page: PAGE, size: BIG_SIZE, is_arranged: true };
    } else {
      data = { page: PAGE, size: BIG_SIZE, is_arranged: false };
    }
    studentsList(data)
      .then((res: any) => {
        try {
          const flatArr = res.data.data.map((item: any, index: number) => {
            const cache = {};
            for (const i in item) {
              if (typeof item[i] === 'object') {
                for (const j in item[i]) {
                  if (item[i][j] === 1) {
                    cache[`${i}_${j}`] = '是';
                  } else if (item[i][j] === 0) {
                    cache[`${i}_${j}`] = '否';
                  } else {
                    cache[`${i}_${j}`] = item[i][j];
                  }
                }
              }
            }
            return {
              ...cache,
              ...item,
              index: index + 1,
            };
          });
          import('../../../utils/ExcleTools').then(excel => {
            const tHeader: string[] = STUDENT_DOWNLOAD_THEADER;
            const filterVal: string[] = STUDENT_DOWNLOAD_FILTER_VALUE; // 等后端字段
            const data = formatJson(filterVal, flatArr);

            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: '学生报名信息',
            });
          });
        } catch (err) {
          message.error('导出Excel出错!!');
        }
        dispatch({
          type: 'CLOSED_LOADING',
        });
      })
      .catch(() => {
        dispatch({
          type: 'CLOSED_LOADING',
        });
      });
  };

  const columns = [
    {
      title: '名字',
      key: 'name',
      dataIndex: 'name',
    },
    {
      title: '老师是否认领',
      key: 'status',
      dataIndex: 'status',
      render: (text: any) => {
        if (text === 0) {
          return <span>未认领</span>;
        }
        if (text === 1) {
          return <span>已认领</span>;
        }
        if (text === 2) {
          return <span>已拒绝</span>;
        }
        return null;
      },
    },
    // {
    //   title: '是否交学费',
    //   key: 'is_paid',
    //   dataIndex: 'is_paid',
    //   render: (text: any) => (text ? <span>已交</span> : <span>未交</span>),
    // },
    // {
    //   title: '应缴学费',
    //   key: 'money',
    //   dataIndex: 'money',
    //   render: (text: any) => <span>{text / 100}元</span>,
    // },
    // {
    //   title: '实缴学费',
    //   key: 'paid',
    //   dataIndex: 'paid',
    //   render: (text: any) => <span>{text / 100}元</span>,
    // },
    {
      title: '是否进班',
      key: 'is_arranged',
      dataIndex: 'is_arranged',
      render: (text: any) => (text ? <span>已进班</span> : <span>未进班</span>),
    },
    {
      title: '监护人',
      key: 'extra',
      dataIndex: 'extra',
      render: (text: any) => text && <span>{text.guardian}</span>,
    },
    {
      title: '老师',
      key: 'teacher',
      dataIndex: 'teacher',
      render: (text: any) => text && <span>{text.name}</span>,
    },
    {
      title: '就读班级和年级',
      key: 'clase',
      dataIndex: 'clase',
      render: (text: any) => text && <span>{text.name}</span>,
    },
    {
      title: '是否退学',
      key: 'extra',
      dataIndex: 'extra',
      render: (text: any) => text && <span>{text.is_out ? '是' : '否'}</span>,
    },
    {
      title: '操作',
      width: 500,
      key: 'option',
      valueType: 'option',
      dataIndex: 'id',
      render: (text: any, object: any) => (
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <Link
            to="/teachingSystem/editStudent"
            onClick={() => {
              sessionStorage.setItem('studentsData', JSON.stringify(object));
            }}
          >
            编辑基本信息
          </Link>
          <Link
            to="/applyManage/applyList/detail"
            onClick={() => {
              sessionStorage.setItem('studentsData', JSON.stringify(object));
            }}
          >
            查看详情
          </Link>
          {!object.status && (
            <a
              onClick={e => {
                e.preventDefault();
                const newVal: any = {
                  status: 1,
                  is_arranged: true,
                };
                const stu = JSON.parse(JSON.stringify(object));
                const residence_images: any = [];
                const health_images: any = [];
                stu.residences.forEach((item: any) => {
                  residence_images.push(item.id);
                });
                stu.healths.forEach((item: any) => {
                  health_images.push(item.id);
                });
                newVal.residence_images = residence_images;
                newVal.health_images = health_images;
                delete stu.parent;
                delete stu.teacher;
                delete stu.clase;
                delete stu.image;
                delete stu.residences;
                delete stu.healths;
                Modal.confirm({
                  content: '确认认领？',
                  onOk: () => {
                    Editstudents({ ...stu, ...newVal }).then((resp: any) => {
                      if (resp.status === 'success') {
                        notification.success({
                          message: '认领成功',
                        });
                        dispatch({
                          type: 'OPEN_LOADING',
                        });
                        studentsList({ ...searchValue, page: pager.current, size: pager.pageSize })
                          .then((res: any) => {
                            if (res.status === 'success') {
                              dispatch({
                                type: 'GET_DATA',
                                payload: res.data.data,
                              });
                              dispatch({
                                type: 'CHANGE_PAGINATION',
                                payload: {
                                  ...pager,
                                  total: res.data.meta.total,
                                },
                              });
                            }
                            dispatch({
                              type: 'CLOSED_LOADING',
                            });
                          })
                          .catch(() => {
                            dispatch({
                              type: 'CLOSED_LOADING',
                            });
                          });
                      }
                    });
                  },
                });
              }}
            >
              认领学生
            </a>
          )}
          {/* <a
            onClick={e => {
              e.preventDefault();
              setAddModal(true);
              sessionStorage.setItem('studentsData', JSON.stringify(object));
            }}
          >
            修改应缴学费
          </a> */}
          <a
            onClick={e => {
              e.preventDefault();
              setParentModal(true);
              sessionStorage.setItem('studentsData', JSON.stringify(object));
            }}
          >
            更改(绑定)家长
          </a>
          <a
            onClick={e => {
              e.preventDefault();
              Modal.confirm({
                content: '确认退学？',
                onOk: () => {
                  setOutModal(true);
                  sessionStorage.setItem('studentsData', JSON.stringify(object));
                },
              });
            }}
          >
            是否退学
          </a>
          <a
            onClick={e => {
              e.preventDefault();
              Modal.confirm({
                content: '确认删除？',
                onOk: () => {
                  delStudent(text).then((resp: any) => {
                    if (resp.data) {
                      notification.success({
                        message: '删除成功',
                      });
                      dispatch({
                        type: 'OPEN_LOADING',
                      });
                      studentsList({ ...searchValue, page: pager.current, size: pager.pageSize })
                        .then((res: any) => {
                          if (res.status === 'success') {
                            dispatch({
                              type: 'GET_DATA',
                              payload: res.data.data,
                            });
                            dispatch({
                              type: 'CHANGE_PAGINATION',
                              payload: {
                                ...pager,
                                total: res.data.meta.total,
                              },
                            });
                          }
                          dispatch({
                            type: 'CLOSED_LOADING',
                          });
                        })
                        .catch(() => {
                          dispatch({
                            type: 'CLOSED_LOADING',
                          });
                        });
                    }
                  });
                },
              });
            }}
          >
            删除
          </a>
        </div>
      ),
    },
  ];

  return (
    <Fragment>
      <Card title="报名列表">
        <MyForm dispatch={dispatch} />
      </Card>
      <Card className="pageCard">
        <Button
          icon="download"
          style={{
            marginBottom: '24px',
          }}
          onClick={() => {
            downloadData(1);
          }}
        >
          导出所有报名学生
        </Button>
        <Button
          type="primary"
          icon="download"
          style={{
            marginBottom: '24px',
            marginLeft: '24px',
          }}
          onClick={() => {
            downloadData(2);
          }}
        >
          导出所有认领学生
        </Button>
        <Button
          type="danger"
          icon="download"
          style={{
            marginBottom: '24px',
            marginLeft: '24px',
          }}
          onClick={() => {
            downloadData(3);
          }}
        >
          导出所有未认领学生
        </Button>
        <TableList
          rowKey="id"
          dataSource={data}
          columns={columns}
          loading={loading}
          pagination={pagination}
          onChange={onChange}
        />
      </Card>
      {addModal && (
        <ApplyModal
          dispatch={dispatch}
          onClose={() => {
            setAddModal(false);
          }}
        />
      )}
      {outModal && (
        <OutModal
          dispatch={dispatch}
          onClose={() => {
            setOutModal(false);
          }}
        />
      )}
      {parentModal && (
        <UpdateParentModal
          dispatch={dispatch}
          onClose={() => {
            setParentModal(false);
          }}
        />
      )}
    </Fragment>
  );
}

export default ApplyList;
